/*
 * @lc app=leetcode.cn id=707 lang=typescript
 *
 * [707] 设计链表
 */

// @lc code=start
class LinkNode {
  val: number;
  next: LinkNode | null;
  constructor(val: number = 0, next: LinkNode | null = null) {
    this.val = val;
    this.next = next;
  }
}
class MyLinkedList {
  size: number = 0;
  dump: LinkNode;
  constructor() {
    this.dump = new LinkNode(-1);
  }

  get(index: number): number {
    if (index < 0 || index >= this.size) {
      return -1;
    }
    let node: LinkNode | null = this.dump;
    for (let i = 0; i <= index; i++) {
      node = node!.next;
    }
    return node!.val;
  }

  addAtHead(val: number): void {
    this.addAtIndex(0, val);
  }

  addAtTail(val: number): void {
    this.addAtIndex(this.size, val);
  }

  addAtIndex(index: number, val: number): void {
    if (index > this.size) return;
    index = Math.max(0, index);
    this.size++;
    let preNode = this.dump;
    for (let i = 0; i < index; i++) {
      preNode = preNode.next!;
    }
    const nextNode = new LinkNode(val);
    nextNode.next = preNode.next;
    preNode.next = nextNode;
  }

  deleteAtIndex(index: number): void {
    if (index < 0 || index >= this.size) return;
    this.size--;
    let preNode = this.dump;
    for (let i = 0; i < index; i++) {
      preNode = preNode.next!;
    }
    preNode.next = preNode.next!.next;
  }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */
// @lc code=end
